package com.shenhaofeng.app.http;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;


/**
 * 参数对象
 * Created by Administrator on 2016/10/12.
 */
public class Params {

    private String[] namesAndValues;


    public Params(String[] namesAndValues) {
        this.namesAndValues = namesAndValues;
    }


    /**
     * 获取指定位置的name
     *
     * @param index
     * @return
     */
    public String name(int index) {
        return namesAndValues[index];
    }


    public String value(int index) {
        return namesAndValues[index + 1];
    }


    /**
     * 获取name集合
     *
     * @return
     */
    public Set<String> names() {
        TreeSet<String> result = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        for (int i = 0, size = size(); i < size; i++) {
            result.add(name(i));
        }
        return Collections.unmodifiableSet(result);
    }


    /**
     * 获取字段值
     *
     * @param name
     * @return
     */
    public String value(String name) {
        for (int i = 0, size = size(); i < size; i++) {
            if (name.equalsIgnoreCase(name(i))) {
                return value(i);
            }
        }
        return null;
    }


    /**
     * 字段数
     *
     * @return
     */
    public int size() {
        return namesAndValues.length / 2;
    }


    /**
     * 参数构建器
     */
    public static class Builder {
        Map<String, String> kvs = new HashMap<>();


        public Builder put(String key, String value) {
            kvs.put(key, value);
            return this;
        }


        public Params build() {
            int size = kvs.size();
            String[] kv = new String[2 * size];
            Iterator<Map.Entry<String, String>> iterator = kvs.entrySet().iterator();
            int i = 0;
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                kv[i * 2] = entry.getKey();
                kv[i * 2 + 1] = entry.getValue();
                i++;
            }
            return new Params(kv);
        }
    }

}
